/*
	Credits:
	http://www.yourhtmlsource.com/javascript/popupwindows.html for the popup tutorial.

	Changelog:
	2009-10-27	v1.02 War links open in new window.
				Also get tagged with visited when clicked.
	2009-12-17	Finally updated for iframes
	2009-12-27	Ajax version
	2010-09-27	Finally fixed for the new ajax call routines.
	2010-10-05	Updated for the new war link syntax, it uses MWid so we need to visit profiles first.
*/

javascript:(function (){
var version='War Hunter v1.08 beta';
try {
	if (document.getElementById('app10979261223_iframe_canvas')) {
		if(confirm('You need to break out the mw-frame first.\nPress OK to do it now.')) {
			window.location.href=document.getElementById('app10979261223_iframe_canvas').src;
			return;
		}
	}
	else if (document.getElementsByClassName('canvas_iframe_util')[0]) {
		if(confirm('You need to break out the mw-frame first.\nPress OK to do it now.')) {
			window.location.href=document.getElementsByClassName('canvas_iframe_util')[0].src;
			return;
		}
	}
	else {
		document.body.parentNode.style.overflowY="scroll";
		document.body.style.overflowX="auto";
		document.body.style.overflowY="auto";
		try { 
			if(typeof FB != 'undefined') {
				FB.CanvasClient.stopTimerToSizeToContent; 
				window.clearInterval(FB.CanvasClient._timer);
				FB.CanvasClient._timer=-1;
			}
			document.getElementById('mw_zbar').innerHTML='';
		}
		catch (fberr) {}
	}
	// from Yevgen Silant'yev, http://joyka.pp.ua/
	function getMWURL() {
		str = document.location;
		str = str.toString();
		beg = str.substring(0,str.indexOf('?')+1);
		str = str.substring(str.indexOf('?')+1);
		str = str.split('&');
		mid = '';
		for(var i=0;i<str.length;i++){
			if(str[i].indexOf('sf_xw_')==0){ mid=mid+str[i]+'&'; }
		}
		return beg+mid;
	}
	if (navigator.appName == 'Microsoft Internet Explorer') { 
		alert('You are using Internet Explorer, this bookmarklet will not work.\nUse Firefox or Chrome instead.');
		return;
	}
	var MWURL = getMWURL();
	var sf_xw_sig = /sf_xw_sig=([a-fA-F0-9]+)/.exec(MWURL);
	var run=1,xmlHTTP,content=document.getElementById('content_row'),debug=false,specialmsg='',output='',
	x=0,second=false,last_url=null,retries=0,tmpkey=false,totalfriends=0,combinedloot='',done=0,list=0,
	mw_url='http://apps.facebook.com/inthemafia/profile.php?id=%7B%22user%22%3A%22ID%22%7D',color='#BCD2EA',
	fb_url='http://www.facebook.com/profile.php?id=',friends_helped=0;
	var wait1=3,wait2=6,skip=0;
	var log_size=20;
	var log_keep=/(active|Facebook|Starting|\[War\])/;
	var userid = /'sf_xw_user_id': '(.+)'/.exec(document.body.innerHTML)[1];
	var fbuserid = FB.Facebook.apiClient.get_session().uid+'';
	var oldfriend, friendid;

	//var mafia_size=$("user_group_size").parentNode.parentNode;
	//mafia_size.innerHTML='<nobr>'+mafia_size.innerHTML.replace(/&nbsp;/g,'')+'</nobr>';
	var newfriends=[],newnames=[],friendslist=[],nameslist=[],friendarray=[],friendsint=[],namesint=[],names=[];
	try {
		//Gift page friends from Francisco Moraes
		var inputs = document.getElementsByTagName("input");
		var c = 0;
		for(i = 0; i < inputs.length; i++) {
			var input = inputs[i];
			if(input.id.indexOf("cb_recip_") == 0) {
				friendsint[c] = input.id.substring(9);
				namesint[c] = input.nextSibling.nodeValue.replace(/^\s+|\s+$/g, '') ;
				c++;
			}
		}
		friends = friendsint;
		names = namesint;
		//alert('Internal friends: '+friends.length+' Names collected: '+names.length);
	}
	catch (interror) { alert(interror); }
	if (friendsint.length > 0) { 
		list=0; 
		specialmsg = '<tr><td colspan="3"><span class="">Found '+friendsint.length+' mafia members.<br />You can only help FB friends so this list could give a lot of not friend errors.</span><br /><span class="bad">Recommendation: Use the Manual list if you have a large non FB-friend mafia.</span></td></tr>';
	}
	if (friendsint.length == 0) { 
		list=1; 
		specialmsg = '<tr><td colspan="3"><span class="bad">No Friends found!</span> <span class="">You have to use the Manual List. Run the bookmarklet on your Gift page to find mafia members.</span><br /><span>You can try also <span class="energy_highlight"><a id="loadfriendslnk" href="#">clicking here</a></span> to attempt friend loading from Facebook.</span></td></tr>';
	}
	// createCookie from Vern's Toolkit http://vern.com/mwtools/
	function createCookie(name,value) {
		// expire one month from now
		var expires = new Date();
		expires.setDate(expires.getDate()+30);
		document.cookie = name+"="+value+";expires="+expires.toGMTString()+"; path=/";
	}

	// readCookie from Vern's Toolkit http://vern.com/mwtools/
	function readCookie(name) {
		var i,
			cookie,
			nameEQ = name+"=",
			cookieArray = document.cookie.split(";");
		for (i=0; i< cookieArray.length; i++) {
			cookie = cookieArray[i];
			while (cookie.charAt(0)==' ')
				cookie = cookie.substring(1,cookie.length);
			if (cookie.indexOf(nameEQ) == 0)
				return cookie.substring(nameEQ.length,cookie.length);
		}
		return null;
	}

	//Pistol Pete FQL code
	function parseFBFr(){
		var fql="SELECT uid,name FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=" + FB.Facebook.apiClient.get_session().uid + ") AND is_app_user = 1 ORDER BY name";
		//alert(fql);
		var f=function(){
			var results=[];
			var friendquicklist;
			return {
				getResults: function(){ return results; },
				process: function(fbfr){
					if (fbfr){
					for(i=0;i<fbfr.length;i++) {
						  //results[results.length]={	'id':fbfr[i].uid, 'name':fbfr[i].name };
						  if (fbfr[i].name != null) {
								friendquicklist += fbfr[i].uid+', '+ fbfr[i].name.replace(/[^A-Za-z0-9 ]/g, '') +'\n';
						}
						  
					}
					}
					else{friendquicklist='Unable to retrieve list.\nTry reloading the game to fix session problems.'}
					//friend=results;
					document.getElementById('friendlist').value = friendquicklist.replace(/undefined/,'');
				}
			};
		}();
		document.getElementById('friendlist').value = 'Loading...Be Patient...';
		FB.Facebook.apiClient.fql_query(fql, f.process);
		return ;
	}
	
	//wait1 = readCookie('spockjobs_wait1');
	//if (wait1) wait1=wait1.replace(/[^0-9]/g,'');
	if ((wait1 == null) || (wait1.length == 0)) { wait1 = 3; }
	//wait2 = readCookie('spockjobs_wait2');
	//if (wait2) wait2=wait2.replace(/[^0-9]/g,'');
	if ((wait2 == null) || (wait2.length == 0)) { wait2 = 6; }
	skip = readCookie('warhunt_skip');
	if (skip) skip=skip.replace(/[^0-9]/g,'');
	if ((skip == null) || (skip.length == 0)) { skip = 0; }
	redo="";

	function myRandom(min,max) {
		return min + Math.floor(Math.round((Math.random() * (max - min))));
	}
	// deliberate pause from Vern's toolkit.js, http://vern.com/mwtools/
	// given a number of seconds, an optional message and a resume
	// function, will pause a few seconds and then execute the function
	function pausing(seconds,message,resume_func) {
		// if the message was left out, shuffle things a bit
		if (typeof(message) == 'function') {
			resume_func = message;
			message = null;
		}
		if (message)
			message=message;
		else
		message='Pausing';
		msg(message+' <span id="seconds">'+seconds+' second'+(seconds==1?'':'s')+'</span>...');
		//var me = this;
		var timer = setInterval(function(){//)
			seconds--;
			if (document.getElementById('seconds'))
				document.getElementById('seconds').innerHTML=seconds+' second'+(seconds==1?'':'s');
			else
				clearInterval(timer);
			if (seconds<=0) {
				clearInterval(timer);
				if (typeof(resume_func) == 'function')
					resume_func();
			}
		},1000);
	}

	var config_html =
	'<style type="text/css">'+
		'.messages img{margin:0 3px;vertical-align:top};'+
		'#close{display:inline};'+	
	'</style>'+
	'<form name="spockform">'+
		'<table class="messages">'+
			'<tr><td colspan="2">Configuration</td><td align="right" style="text-align:right;">'+version+' - <a href="http://www.spockholm.com/mafia/bookmarklets.php" target="_top">Spockholm Mafia Tools</a> - <a href="#" id="close"><img src="http://www.spockholm.com/mafia/stop.gif" title="Close" width="16" height="16"></a></td></tr>'+
			specialmsg+
			'<tr><td>Delay interval:</td><td><input type="text" name="wait1" id="wait1" value="'+wait1+'" size="3">-<input type="text" name="wait2" id="wait2" value="'+wait2+'" size="3"></td><td>Delay in seconds between checks.</td></tr>'+
			'<tr><td>Skip:</td><td><input type="text" name="skip" id="skip" value="'+skip+'"></td><td>Friends to skip</td></tr>'+
			'<tr>'+
				'<td>List: </td>'+
				'<td>'+
					'<select name="list" id="list">';
					if (list==1) {
						config_html += '<option value="1"'+(list==1?" selected":"")+'>Manual List</option>';
					}
					else {
						config_html += '<option value="0"'+(list==0?" selected":"")+'>Internal List</option>';
						config_html += '<option value="1"'+(list==1?" selected":"")+'>Manual List</option>';
					}
	config_html += '</select>'+
				'</td>'+
				'<td colspan="2"> Select which source to use to find your list of mafia.</td>'+
			'</tr>'+
			'<tr id="manual_list">'+
				'<td>Friend List:</td>'+
				'<td colspan="3"><textarea name="friendlist" id="friendlist" class="instructions" rows="25" cols="50">'+
					'Enter in this box a list of your mafia.\n'+
					'Enter an ID and (optional) Name, one per line.\n'+
					'Lines that do not begin with a number will be discarded.\n'+
					'\n'+
					'Examples:\n'+
					'123123123123,One Two Three\n'+
					'456456456 Four Five\n'+
					'7898798343\n'+
				'</textarea></td>'+
			'</tr>'+
			'<tr><td>Restart: </td><td><input type="checkbox" name="redo" id="redo" '+redo+'/></td><td colspan="2"> Restart processing from the beginning when we are done.</td>'+
			'<tr><td>Debug: </td><td><input type="checkbox" name="debug" id="debug" /></td><td colspan="2"> Output messages for debugging?</td></tr>'+
			'<tr><td colspan="3"><a class="sexy_button" id="start">Start</a></td></tr>'+
		'</table>'+
	'</form>';

	var running_html = 
	'<style type="text/css">'+
		'.messages img{margin:0 3px;vertical-align:top}'+
		'.messages input {border: 1px solid #FFF;margin 0;padding 0;background: #000; color: #FFF; width: 20px;}'+
		'#play{display:none}'+
		'#pause{display:inline}'+
		'#close{display:inline}'+
	'</style>'+
	'<table class="messages">'+
	'<tr>'+
		'<td><a href="#" id="next">Next friend</a></td><td colspan="2" style="text-align:right;">'+version+' - <a href="http://www.spockholm.com/mafia/bookmarklets.php" target="_top">Spockholm Mafia Tools</a> - <a href="#" id="play"><img src="http://www.spockholm.com/mafia/play.gif" title="Play" width="16" height="16" /></a> <a href="#" id="pause"><img src="http://www.spockholm.com/mafia/pause.gif" title="Pause" width="16" height="16" /></a> <a href="#" id="close"><img src="http://www.spockholm.com/mafia/stop.gif" title="Close" width="16" height="16" /></a></td>'+
	'</tr>'+
	'<tr>'+
		'<td width="100">Progress:</td>'+
		'<td><span id="progress"></span> &nbsp; (<a href="#" id="remaining">Popup remaining</a>)</td>'+
		'<td align="right" style="text-align:right;">Delay: <input id="delay1" name="delay1" type="text" value="'+wait1+'" maxlength="2" /> - <input id="delay2" name="delay2" type="text" value="'+wait2+'" maxlength="2" /> sec</td>'+
	'</tr>'+
	'<tr>'+
		'<td>Status:</td>'+
		'<td colspan="2" id="status"></td>'+
	'</tr>'+
	'<tr>'+
		'<td valign="top"><a href="#" id="logshow">Showing</a> Log:</td>'+
		'<td colspan="2" id="log" valign="top"></td>'+
	'</tr>'+
	'</table>';
	function create_div() {
		if(document.getElementById('spockdiv')) {
			document.getElementById('spockdiv').innerHTML = config_html;
		}
		else {
			var spock_div=document.createElement("div");
			spock_div.id = 'spockdiv';
			spock_div.innerHTML = config_html;
			content.insertBefore(spock_div, content.firstChild);
		}
	}
	create_div();
	document.getElementById('close').onclick=function(e) {
		run = 0;
		document.getElementById("content_row").removeChild(document.getElementById("spockdiv"));
		return false;
	}
	document.getElementById("list").onchange=function(e) {
		if (document.getElementById("list").value == 0) { document.getElementById("manual_list").style.display = 'none'; }
		else { document.getElementById("manual_list").style.display = 'table-row'; list=1; }
	}
	document.getElementById("list").onchange();
	document.getElementById("friendlist").onfocus=function(e) {
		document.getElementById("friendlist").value="";
		document.getElementById("friendlist").style.color="#000";
		document.getElementById("friendlist").onfocus=null;
	}
	if (list == 1) {
		document.getElementById('loadfriendslnk').onclick=function(e) {
			document.getElementById("friendlist").focus();
			parseFBFr();
		};
	}	
	
	//start start function
	//document.getElementById('start').onclick=function(e) {
	function start() {
		run = 1;
		wait1 = parseInt(document.spockform.wait1.value);
		//createCookie("spockjobs_wait1",wait1);
		wait2 = parseInt(document.spockform.wait2.value);
		//createCookie("spockjobs_wait2",wait2);
		skip = parseInt(document.spockform.skip.value);
		createCookie("warhunt_skip",skip);

		if (document.spockform.redo.checked) { redo = "checked"; }
		else { redo = ""; }
		if (document.spockform.debug.checked) { debug = true; }

		if (list == 1) {
			friendarray=document.spockform.friendlist.value.split("\n");
			for (i=0; i<friendarray.length; i++) {
				if (m=/^([0-9]+)[,\s]*(.*)$/.exec(friendarray[i])) {
					friendslist[i] = m[1];
					if (m[2]) { nameslist[i] = m[2]; }
				}
			}
			delete friendarray;
			friends = friendslist;
			names = nameslist;
		}
		if ((list == 1) && (friends.length == 8) || (friends.length == 0)) {
			alert('You did not fill in the manual list properly. It should be a list containing numbers on new lines.\nList FB friends on the testing page http://www.spockholm.com/mafia/testing.php\n will create this list for you.');
			return;
		}
		//comparing the internal and the manual lists to filter friends
		if ((friendslist.length > 0) && (friendsint.length > 0)) {
			c = 0;
			for(i = 0; i < friendslist.length; i++) {
				if(friendsint[i].indexOf(friendslist[i])) {
				//if(friendslist[i].toString() in friendsint) { 
					newfriends[c++] = friendslist[i]; 
					newnames[c] = nameslist[i]; 
				}
			}
			friends=[],names=[];
			friends = newfriends;
			names = newnames;
			//alert('Both in internal and manual friends: '+friends.length);
		}
		//clean up unused arrays
		if (newfriends.length > 0) { delete newfriends; }
		if (newnames.length > 0) { delete newnames; }
		if (friendslist.length > 0) { delete friendslist; }
		if (nameslist.length > 0) { delete nameslist; }
		if (friendsint.length > 0) { delete friendsint; }
		if (namesint.length > 0) { delete namesint; }

		document.getElementById('spockdiv').innerHTML = running_html;
		document.getElementById('next').onclick=function(e) {
			done++;
			friends=friends.slice(1);
			run=1;
			document.getElementById("pause").style.display = 'none';
			document.getElementById("play").style.display = 'inline';
			search();
			return false;
		}
		document.getElementById('pause').onclick=function(e) {
			run = 0;
			document.getElementById("pause").style.display = 'none';
			document.getElementById("play").style.display = 'inline';
			return false;
		}
		document.getElementById('play').onclick=function(e) {
			run = 1;
			document.getElementById("play").style.display = 'none';
			document.getElementById("pause").style.display = 'inline';
			msg('Resuming job searching... (<a href="'+last_url+'">url</a>)');
			retries = 0;
			request(last_url);
			return false;
		}
		document.getElementById('close').onclick=function(e) {
			run = 0;
			document.getElementById("content_row").removeChild(document.getElementById("spockdiv"));
			return false;
		}
		document.getElementById('delay1').onkeyup=function(e) {
			time = parseInt(document.getElementById('delay1').value);
			if((time < 0) || (!time)) { wait1 = 0; }
			else { wait1 = time; }
			//createCookie('spockaX_wait1',wait1);
			document.getElementById('delay1').value=wait1;
		}
		document.getElementById('delay2').onkeyup=function(e) {
			time = parseInt(document.getElementById('delay2').value);
			if((time < 0) || (!time)) { wait2 = 0; }
			else { wait2 = time; }
			//createCookie('spockaX_wait2',wait2);
			document.getElementById('delay2').value=wait2;
		}
		// document.getElementById('logsize').onkeyup=function(e) {
			// log_size = parseInt(document.getElementById('logsize').value);
			// if((log_size < 0) || (!log_size)) { log_size = 20; }
			// else { log_size = log_size; }
			// createCookie('spockaX_logsize',log_size);
			// document.getElementById('logsize').value=log_size;
		// }
		document.getElementById('logshow').onclick=function(e) {
			var row = document.getElementById("log");
			if (row.style.display == '') { 
				row.style.display = 'none'; 
				document.getElementById("logshow").innerHTML = 'Hiding';
			}
			else { 
				row.style.display = '';
				document.getElementById("logshow").innerHTML = 'Showing';
			}
			return false;
		}
		log('Click [Help in War] to load the war in the active window, the bookmarklet will continue in the background.');
		
		savedfiends = [];
		savedfriends = friends;
		if (skip >= friends.length -1) { skip=0; }
		if (skip > 0) {
			log(timestamp()+'Skipping '+skip+' friends of '+friends.length+'.');
			friends=friends.slice(skip);
		}
		//log(timestamp()+'Number of friends existing in both lists: '+newfriends.length);
		totalfriends = friends.length;
		document.getElementById('progress').innerHTML = done+' of '+friends.length+' &nbsp; <span class="more_in">('+(done/totalfriends*100).toFixed(1)+'%)</span>';
		log(timestamp()+'Starting check of '+friends.length+' friends.');
		document.getElementById('remaining').onclick=dirtypop;
		friendid = friends[0];
		search();
	}
	//end start function
	document.getElementById('start').onclick=start;

	function unix_timestamp() {
		return parseInt(new Date().getTime().toString().substring(0, 10))
	}
	function request(url) {
		oldfriend = friendid = friends[0];
		//friendid = friends[0];
		done++;
		createCookie("warhunt_skip",parseInt(skip+done));
		if (run == 1) {
			//document.getElementById('inner_page').addEventListener('DOMSubtreeModified',state_change,false);
			//url = url.replace(/sf_xw_sig=([^&]+)/.exec(url)[1],local_xw_sig);
			//currentPageCount = pageCount;
			//do_ajax('inner_page', url, 1, 1);
			//console.log(url);
			var preurl = 'http://facebook.mafiawars.com/mwfb/remote/';
			//console.log(preurl+url);
			cb = fbuserid+unix_timestamp();
			ts = unix_timestamp();
			var params = { 
				'ajax': 1, 
				'liteload': 1, 
				'sf_xw_user_id': userid,
				'sf_xw_sig': local_xw_sig,
				'xw_client_id' : 8,
				'skip_req_frame': 1
			};
			$.ajax({
				type: "POST",
				url: preurl+url+'&cb='+cb,
				//url: preurl+url+'&xw_client_id=8',
				data: params,
				success: function (msg){
					state_change(msg);
				},
				error: function(request,error){
					log(timestamp()+request.status+' '+(error!=undefined?error:request.responseText)+' Error when loading page, retry #'+retries);
					retry('Some sort of problem when loading page, retrying...'); 
                }
			});
		} else {
			msg('Paused searching.');
		}
		last_url=url;
	}
	function war_url(id) {
		return 'html_server.php?xw_controller=war&xw_action=view&xw_city=&xw_person='+userid.replace(/[^\d]/g,'')+'&leader_id='+id;
	}
	function profile_url(id) {
		return 'html_server.php?xw_controller=stats&xw_action=view&xw_city=&user='+id;
	}
	function search() {
		if (friends.length == 0 && redo == "") {
			msg(timestamp()+'Done looking for active wars. Peace!');
			document.getElementById("play").style.display = 'none';
			document.getElementById("pause").style.display = 'none';
			createCookie("warhunt_skip",0);
			//document.getElementById('inner_page').removeEventListener('DOMSubtreeModified',state_change,false);
		}
		else if (friends.length == 0 && redo == "checked") {
			friends=savedfriends;
			totalfriends=friends.length;
			done=0;
			skip=0;
			createCookie("warhunt_skip",skip);
			log(timestamp()+'<span class="money">Starting again from the beginning.</span>');
			search();
		}
		else {
			function f() {
				//last_url=war_url(friends[0]);
				last_url=profile_url(friends[0]);
				msg('Checking for war with '+friends[0]+' as leader (<a href="'+last_url+'">url</a>)');
				request(last_url);
			}
			wait = myRandom(parseInt(wait1),parseInt(wait2));
			pausing(wait,'Waiting for ',f);
		}
	}

	function dirtypop() {
		var generator=window.open('','name','height=500,width=500');
		generator.document.write('<html><head><title>Mafia remaining to check</title>');
		generator.document.write('</head><body>');
		generator.document.write('<pre>Number of friends in this list: '+friends.length+'</pre><textarea rows="20">');
		for(i = 0; i < friends.length; i++) {
			generator.document.write(friends[i]+'\n');
		}
		generator.document.write('</textarea><pre><a href="javascript:self.close()">Close</a> the popup.</pre>');
		generator.document.write('</body></html>');
		generator.document.close();
	}
	function log(s) {
		document.getElementById('delay1').value=wait1;
		document.getElementById('delay2').value=wait2;
		document.getElementById('progress').innerHTML = done+' of '+totalfriends+' &nbsp; <span class="more_in">('+(done/totalfriends*100).toFixed(1)+'%)</span>';
		//document.getElementById('debug').innerHTML = 'Debug '+(debug=='true'?"on":"off");
		var l=document.getElementById('log');
		if (s) {
			l.innerHTML=s+'<br />'+l.innerHTML;
			 //logtrunc(s,log_size,log_keep);
		}
	}
	function msg(s) {
			document.getElementById('status').innerHTML=s;
	}
	function commas(s) {
		while (d=/(\d+)(\d{3}.*)/.exec(s)) {
			s = d[1] + ',' + d[2];
		}
		return s;
	}
	function retry(s) {
	  if (retries > 10) {
		msg(s + ', not retrying any more.');
	  }
	  else {
			setTimeout(function(){
				retries++;
				msg(s+'; retry #'+retries+'...');
				request(last_url);
			},5000);
		}
	}
	function mwlink() {
		return '<span class="more_in">[<a href="'+mw_url.replace(/ID/,oldfriend)+'">MW</a>]</span>';
	}
	function fblink() {
		return '<span class="more_in">[<a href="'+fb_url+oldfriend+'">FB</a>]</span>';
	}
	function fblink2() {
		return '<a href="'+fb_url+id+'">'+oldfriend+'</a>';
	}
	function warlink() {
		return '<span class="more_in">[<a href="http://apps.facebook.com/inthemafia/track.php?next_controller=war&next_action=view&zy_track=newsfeed&ztrack_category=story_war_declared_stream&next_params=%7B%22leader_id%22%3A%22'+oldfriend+'%22%7D&_fb_q=1&ref=nf" target="_blank" onclick="this.innerHTML=\'Visited War\';">War</a>]</span>';
	}
	// From Vern's toolkit.js, http://vern.com/mwtools/
	// log puts a message in the log array and outputs it
	// limit is how many log lines we keep (0 == infinite)
	// keep is a regex of lines that we never delete
	logs = [];
	extralog = [];
	function logtrunc(message,limit,keep) {
		logs.unshift(message);
		if (limit > 0) {
			if (logs.length>limit) {
				message=logs.pop();
				if ((keep.test) && (keep.test(message)))
						extralog.unshift(message);
			}
		}
		if ((document.getElementById('log')) && (document.getElementById('log').nodeName == 'TD')) {
			document.getElementById('log').innerHTML=logs.concat(extralog,'').join('<br/>');
		}
	}
	function timestamp() {
		now = new Date();
		var CurH = now.getHours();
		CurH = (CurH<10?"0"+CurH:CurH);
		var CurM = now.getMinutes();
		CurM = (CurM<10?"0"+CurM:CurM);
		return '<span class="more_in">['+CurH+':'+CurM+']</span> ';
	}
	var expnow,expnext,stamina,energy,ratiolvl3;
	function stats_ratios(s) {
		if (/user_info_update/.test(s)) { var s=s.substr(0,s.indexOf('user_info_update')); }
		document.getElementById('user_cash_nyc').innerHTML = /user_cash_nyc.*?"(.*?)"/.exec(s)[1];
		document.getElementById('user_cash_cuba').innerHTML = /user_cash_cuba.*?"(.*?)"/.exec(s)[1];
		document.getElementById('user_cash_moscow').innerHTML = /user_cash_moscow.*?"(.*?)"/.exec(s)[1];
		document.getElementById('user_cash_bangkok').innerHTML = /user_cash_bangkok.*?"(.*?)"/.exec(s)[1];
		document.getElementById('user_cash_vegas').innerHTML = /user_cash_vegas.*?"(.*?)"/.exec(s)[1];
		expnow = parseInt(/user_experience.*?(\d+)/.exec(s)[1]);
		expnext = parseInt(/exp_for_next_level.*?(\d+)/.exec(s)[1]);
		expneed = eval(expnext-expnow);

		if (document.getElementById('exp_to_next_level')) {
			document.getElementById('exp_to_next_level').innerHTML = expneed;
		}
		else {
			document.getElementById('user_experience').innerHTML = expnow;
			document.getElementById('exp_for_next_level').innerHTML = expnext;
		}	
		
		energy = parseInt(/user_energy.*?(\d+)/.exec(s)[1]);
		document.getElementById('user_energy').innerHTML = energy;
		stamina = parseInt(/user_stamina.*?(\d+)/.exec(s)[1]);
		document.getElementById('user_stamina').innerHTML = stamina;
		
		ratiolvl=eval(expneed/energy);
		ratiolvl2=eval(expneed/stamina);
		ratiolvl3=eval(expneed/(parseInt(energy)+parseInt(stamina)));
		(Math.abs(ratiolvl)<5)?(d=2):(d=0);
		(Math.abs(ratiolvl2)<5)?(d2=2):(d2=0);
		(Math.abs(ratiolvl3)<5)?(d3=2):(d3=0);
		if(ratiolvl=='Infinity') { ratiolvl=0; d=0; }
		if(ratiolvl2=='Infinity') { ratiolvl2=0; d2=0; }
		if(ratiolvl3=='Infinity') { ratiolvl3=0; d3=0; }
		
		if (document.getElementById('exp_to_next_level')) {
			document.getElementsByClassName('experience')[0].innerHTML='(<span class="energy_highlight">'+(ratiolvl).toFixed(d)+'</span><img src="http://mwfb.static.zynga.com/mwfb/graphics/icon_energy_16x16_01.gif" width="12" height="12" title="Exp needed per Energy">)(<span class="energy_highlight">'+(ratiolvl2).toFixed(d2)+'</span><img src="http://mwfb.static.zynga.com/mwfb/graphics/icon_stamina_16x16_01.gif" width="12" height="12" title="Exp needed per Stamina">) <span class="more_in">'+(ratiolvl3).toFixed(d3)+'</span>';
			document.getElementById('level_bar').style.width = /percent_complete.*?(\d+)/.exec(s)[1]+'%';
		}
		else {
			document.getElementById('user_experience').innerHTML='(<span class="energy_highlight">'+(ratiolvl).toFixed(d)+'</span><img src="http://mwfb.static.zynga.com/mwfb/graphics/icon_energy_16x16_01.gif" width="12" height="12" title="Exp needed per Energy">)(<span class="energy_highlight">'+(ratiolvl2).toFixed(d2)+'</span><img src="http://mwfb.static.zynga.com/mwfb/graphics/icon_stamina_16x16_01.gif" width="12" height="12" title="Exp needed per Stamina">) <span class="more_in">'+(ratiolvl3).toFixed(d3)+'</span>';
			document.getElementById('level_bar_new_header').style.width = /percent_complete.*?(\d+)/.exec(s)[1]+'%';
		}
		
		//document.getElementById('user_stats').getElementsByClassName('experience')[0].innerHTML='Exp Need: <span class="energy_highlight">'+expneed+'</span><br>(<span class="energy_highlight">'+(ratiolvl).toFixed(d)+'</span><img src="http://mwfb.static.zynga.com/mwfb/graphics/icon_energy_16x16_01.gif" width="12" height="12" title="Exp needed per Energy">)(<span class="energy_highlight">'+(ratiolvl2).toFixed(d2)+'</span><img src="http://mwfb.static.zynga.com/mwfb/graphics/icon_stamina_16x16_01.gif" width="12" height="12" title="Exp needed per Stamina">)<span class="more_in">'+(ratiolvl3).toFixed(d3)+'</span>';
	}
	function state_change(s) {
		//stats_ratios(s);
		if (/Choose a (Target|side)/.test(s)) {
			//log(timestamp()+oldfriend+' has a <span class="good">war active</span>! '+mwlink()+fblink()+warlink());
			friends=friends.slice(1);
			search();
			return;
		}
		// else if (/Time remaining/.test(s)) {
			// log(timestamp()+oldfriend+' has a <span class="good">war active</span>! '+mwlink()+fblink()+warlink());
			// friends=friends.slice(1);
			// search();
			// return;
		// }
		// else if (/Start a New War in/.test(s)) {
			// if (debug) { log(timestamp()+oldfriend+' Your own war loaded?. '+mwlink()+fblink()+warlink()); }
			// log();
			// friends=friends.slice(1);
			// search();
			// return;
		// }
		// else if (/ending the war/.test(s)) {
			// if (debug) { log(timestamp()+oldfriend+' This war is over, cooldown left. '+mwlink()+fblink()+warlink()); }
			// log();
			// friends=friends.slice(1);
			// search();
			// return;
		// }
		// else if (/This war is already over/.test(s)) {
			// if (debug) { log(timestamp()+oldfriend+' This war is over, cooldown left. '+mwlink()+fblink()+warlink()); }
			// log();
			// friends=friends.slice(1);
			// search();
			// return;
		// }
		// else if (/This war is over/.test(s)) {
			// if (debug) { log(timestamp()+oldfriend+' This war is over, cooldown left. '+mwlink()+fblink()+warlink()); }
			// log();
			// friends=friends.slice(1);
			// search();
			// return;
		// }
		// else if (/(won the war)|(You lost the war)/.test(s)) {
			// if (debug) { log(timestamp()+oldfriend+' War already ended '+mwlink()+fblink()+warlink()); }
			// log();
			// friends=friends.slice(1);
			// search();
			// return;
		// }
		// else if (/>Declare War</.test(s)) {
			// if (debug) { log(timestamp()+oldfriend+' No war active, you can declare one. '+mwlink()+fblink()+warlink()); }
			// log();
			// friends=friends.slice(1);
			// search();
			// return;
		// }
		// else if (/You are not friends with this person/.test(s)) {
			// log(timestamp()+oldfriend+' Not a facebook friend. '+mwlink()+fblink()+warlink());
			// friends=friends.slice(1);
			// search();
			// return;
		// }
		// else if (/You are not currently in/.test(s)) {
			// log(timestamp()+oldfriend+' Not in mafia together. '+mwlink()+fblink()+warlink());
			// friends=friends.slice(1);
			// search();
			// return;
		// }
		// else if (mwid=/xw_controller=war.*?leader_id=p[%7C\|]+(\d+).*?Help in War/.exec(s)) {
			// msg('Loading friends war page...');
			// log('Loading friends war page...');
			// console.log(war_url('p%7C'+mwid[1]));
			// request(war_url('p%7C'+mwid[1]));
		// }
		else if (warurl=/xw_controller=war&xw_action=view&xw_city=(\d)&tmp=([a-f0-9]+)&cb=([a-f0-9]+)&xw_person=(\d+)&leader_id=p%7C(\d+)/.exec(s)) {
			//msg('Loading friends war page...');
			log(timestamp()+'Found a link to help with war. '+mwlink()+fblink()+'[<a href="#" onclick="this.style.color=\'#CCCCCC\';this.innerHTML=\'Visited War\'; do_ajax(\'inner_page\', \'remote/html_server.php?xw_controller=war&xw_action=view&xw_city='+warurl[1]+'&tmp='+warurl[2]+'&cb='+warurl[3]+'&xw_person='+warurl[4]+'&leader_id=p%7C'+warurl[5]+'\', 1, 1, 0, 0);">Help in War</a>].');
			//console.log('html_server.php?xw_controller=war&xw_action=view&xw_city='+warurl[1]+'&tmp='+warurl[2]+'&cb='+warurl[3]+'&xw_person='+warurl[4]+'&leader_id=p%7C'+warurl[5]);
			//request('html_server.php?xw_controller=war&xw_action=view&xw_city='+warurl[1]+'&tmp='+warurl[2]+'&cb='+warurl[3]+'&xw_person='+warurl[4]+'&leader_id=p%7C'+warurl[5]);
			friends=friends.slice(1);
			search();
			return;
		}
		else {
			//log(timestamp()+oldfriend+' Not sure what page was loaded, going to next friend.');
			friends=friends.slice(1);
			search();
			return;
		}
		retries = 0;
	}

	//testing to add analytics
	function loadContent(file){
		var head = document.getElementsByTagName('head').item(0)
		var scriptTag = document.getElementById('loadScript');
		if(scriptTag) head.removeChild(scriptTag);
			script = document.createElement('script');
			script.src = file;
			script.type = 'text/javascript';
			script.id = 'loadScript';
			head.appendChild(script);
	}
	loadContent('http://www.google-analytics.com/ga.js');
	try {
	var pageTracker = _gat._getTracker("UA-8435065-3");
	pageTracker._trackPageview();
	pageTracker._trackPageview("/script/WarHunter"); 
	} catch(err) {}
	//end analytics

	} //end try
	catch(mainerr) {
		var spock_div=document.getElementById('spockdiv');
		if(spock_div) {
			spock_div.innerHTML='';
		}
		alert('Some error occured, Job Helper not loaded.\nDid you run it on your gift page or unframed MW page?\nIf you did, report the message below (not this text) to Spockholm:\n\n'+version+'\n'+mainerr);
	}
}())